﻿#define _CRT_SECURE_NO_WARNINGS

#include "Tree.h"
#include "Queue.h"

//前序遍历
void FrontOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%c ", root->data);
	FrontOrder(root->left);
	FrontOrder(root->right);

}

//中序遍历
void InOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	InOrder(root->left);
	printf("%c ", root->data);
	InOrder(root->right);
}

//后序遍历
void BackOrder(Tree* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	BackOrder(root->left);
	BackOrder(root->right);
	printf("%c ", root->data);

}


// 二叉树节点个数
int BinaryTreeSize(Tree* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

// 二叉树叶子节点个数
int BinaryTreeLeafSize(Tree* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);

}

// 二叉树第k层节点个数
int BinaryTreeLevelKSize(Tree* root, int k)
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

// 二叉树查找值为x的节点
Tree* BinaryTreeFind(Tree* root, TRType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->data == x)
	{
		return root;
	}
	Tree* rootLeft = BinaryTreeFind(root->left, x);
	if (rootLeft)
	{
		return rootLeft;
	}
	Tree* rootRight = BinaryTreeFind(root->right, x);
	if (rootRight)
	{
		return rootRight;
	}
	return NULL;
	
}

//⼆叉树的深度/⾼度
int BinaryTreeDepth(Tree* root)
{
	if (root==NULL)
	{
		return 0;
	}
	int left = BinaryTreeDepth(root->left);

	int right = BinaryTreeDepth(root->right);

	return 1 + (left > right ? left : right);
}

// 层序遍历---上->下，左->右
void BinaryTreeLevelOrder(Tree* root)
{
	Queue q;
	QueInit(&q);
	QuePush(&q, root);
	while (!QueEmpty(&q))
	{
		Tree* top = QueFront(&q);
		QuePop(&q);
		printf("%c ", top->data);
		if (top->left)
			QuePush(&q, top->left);
		if (top->right)
			QuePush(&q, top->right);
	}
}
// 判断二叉树是否是完全二叉树
int BinaryTreeComplete(Tree* root)
{
	Queue q;
	QueInit(&q);
	QuePush(&q, root);
	while (!QueEmpty(&q))
	{
		Tree* top = QueFront(&q);
		if (top==NULL)
		{
			break;
		}
		QuePop(&q);
		QuePush(&q, top->left);
		QuePush(&q, top->right);
	}
	while (!QueEmpty(&q))
	{
		if (QueFront(&q) != NULL)
			return false;
		QuePop(&q);
	}
	return true;
}
